//
//  VerificationCodeView.m
//  MyFramework
//
//  Created by 余洋 on 2018/10/24.
//  Copyright © 2018 余洋. All rights reserved.
//

#import "VerificationCodeView.h"
#import "Masonry.h"

@interface VerificationCodeView ()<UITextViewDelegate>

@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) NSMutableArray *lines;
@property (nonatomic, strong) NSMutableArray *labels;
@property (nonatomic, strong) NSMutableArray *views;
@property (nonatomic, strong) UIView *maskView;

@end

@implementation VerificationCodeView

-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        self.maxLenght = 4;
        self.uncheckColor = RGBA(0xE6E6E6, 1);
        self.checkColor = RGBA(0xEF6D36, 1);
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)createView {
    //创建视图
    if (self.maxLenght <= 0) {
        return;
    }
    [self addSubview:self.maskView];
    [self.maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(self);
        make.centerY.equalTo(self);
        make.centerX.equalTo(self);
    }];
    [self.maskView addSubview:self.textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.maskView);
    }];
    //计算两个框之间的间距
    CGFloat padding = (CGRectGetWidth(self.frame) -_maxLenght*CGRectGetHeight(self.frame))/(self.maxLenght - 1);
    UIView *lastView;
    for (int i=0; i<self.maxLenght; i++) {
        UIView *subView = [UIView new];
        subView.backgroundColor = [UIColor clearColor];
        subView.layer.masksToBounds = YES;
        subView.layer.cornerRadius = 4.f;
        subView.layer.borderWidth = 0.5;
        subView.userInteractionEnabled = NO;
        [self.maskView addSubview:subView];
        [subView mas_makeConstraints:^(MASConstraintMaker *make) {
            if (lastView) {
                make.left.equalTo(lastView.mas_right).with.offset(padding);
            } else {//第一个视图
                make.left.equalTo(self.maskView);
            }
            make.centerY.equalTo(self.maskView);
            make.height.equalTo(self.maskView.mas_height);
            make.width.equalTo(self.maskView.mas_height);
        }];
        UILabel *label = [UILabel new];
        label.font = [UIFont systemFontOfSize:38.f];
        [subView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(subView);
            make.centerY.equalTo(subView);
        }];
        lastView = subView;
        //光标
        UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake((CGRectGetHeight(self.frame)-2)/2,5,2,(CGRectGetHeight(self.frame)-10))];
        CAShapeLayer *line = [CAShapeLayer layer];
        line.path = path.CGPath;
        line.fillColor = self.checkColor.CGColor;
        [subView.layer addSublayer:line];
        //初始化状态
        if (i == 0) {
            [line addAnimation:[self opacityAnimation] forKey:@"OpacityAnimation"];
            line.hidden = NO;
            subView.layer.borderColor = self.checkColor.CGColor;
        } else {
            line.hidden = YES;
            subView.layer.borderColor = self.uncheckColor.CGColor;
        }
        [self.views addObject:subView];
        [self.labels addObject:label];
        [self.lines addObject:line];
    }
    [self.maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(lastView?lastView.mas_right:@(0));
    }];
    [self startEdit];
}

- (void)startEdit {
    [self.textView becomeFirstResponder];
}

- (void)endEdit {
    [self.textView resignFirstResponder];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    NSString *value = textView.text;
    value = [value stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (value.length >= self.maxLenght) {
        value = [value substringToIndex:self.maxLenght];
        [self endEdit];
    }
    textView.text = value;
    for (int i=0; i<self.views.count; i++) {
        UILabel *label = self.labels[i];
        if (i < value.length) {
            label.text = [value substringWithRange:NSMakeRange(i, 1)];
            [self changeViewLayerByIndex:i lineHidden:YES];
        } else {
            [self changeViewLayerByIndex:i lineHidden:i==value.length?NO:YES];
            label.text = @"";
        }
    }
    if (self.valueChangeBlock) {
        self.valueChangeBlock(value);
    }
}

- (void)changeViewLayerByIndex:(NSInteger)index lineHidden:(BOOL)hidden {
    UIView *view = self.views[index];
    view.layer.borderColor = hidden ? self.uncheckColor.CGColor : self.checkColor.CGColor;
    CAShapeLayer *line = self.lines[index];
    if (hidden) {
        [line removeAnimationForKey:@"OpacityAnimation"];
    }else{
        [line addAnimation:[self opacityAnimation] forKey:@"OpacityAnimation"];
    }
    line.hidden = hidden;
}

//光标动画
- (CABasicAnimation *)opacityAnimation {
    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.fromValue = @(1.0);
    opacityAnimation.toValue = @(0.0);
    opacityAnimation.duration = 0.9;
    opacityAnimation.repeatCount = HUGE_VALF;
    opacityAnimation.removedOnCompletion = YES;
    opacityAnimation.fillMode = kCAFillModeForwards;
    opacityAnimation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    return opacityAnimation;
}

- (NSMutableArray *)lines {
    if (!_lines) {
        _lines = [NSMutableArray array];
    }
    return _lines;
}

- (NSMutableArray *)labels {
    if (!_labels) {
        _labels = [NSMutableArray array];
    }
    return _labels;
}

- (NSMutableArray *)views {
    if (!_views) {
        _views = [NSMutableArray array];
    }
    return _views;
}

- (UITextView *)textView {
    if (!_textView) {
        _textView = [UITextView new];
        _textView.tintColor = [UIColor clearColor];
        _textView.backgroundColor = [UIColor clearColor];
        _textView.textColor = [UIColor clearColor];
        _textView.delegate = self;
        _textView.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _textView;
}

- (UIView *)maskView {
    if (!_maskView) {
        _maskView = [UIView new];
        _maskView.backgroundColor = [UIColor clearColor];
    }
    return _maskView;
}
@end
